package com.jxin.mall.weixin.service;

import com.jxin.mall.config.parent.BaseService;
import com.jxin.mall.entity.entity.GlobalRsp;
import com.jxin.mall.weixin.service.api.WxAccessService;
import com.jxin.mall.weixin.service.entity.dto.rsp.WxUserRspDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.web.bind.annotation.RestController;

/**
 * 微信授权服务实现类
 * @author  蔡佳新
 * @version 1.0
 * @since   jdk 1.8
 */
@RestController
@AllArgsConstructor
@Slf4j
public class WxAccessServiceImpl extends BaseService implements WxAccessService {
    /**微信服务接口*/
    private final WxMpService wxService;
    /**
     * 获取授权url
     * @param  backUrl 回调地址
     * @return 全局响应参数
     * @author 蔡佳新
     */
    @Override
    public GlobalRsp<String> getAccessUrl(String backUrl) {
        return createSuccessWithData(wxService.oauth2buildAuthorizationUrl(backUrl, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null));
    }
    /**
     * 获取微信用户信息
     * @param  accessToken 微信授权令牌
     * @return 全局响应参数
     * @author 蔡佳新
     */
    @Override
    public GlobalRsp<WxUserRspDTO> getWxUser(String accessToken) {
        WxMpUser wxMpUser = null;
        try {
            wxMpUser = wxService.oauth2getUserInfo(wxService.oauth2getAccessToken(accessToken), null);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
        }
        if(wxMpUser == null){
            return createFaildWithData(null);
        }
        return createSuccessWithData(WxUserRspDTO.builder()
                                                 .openId(wxMpUser.getOpenId())
                                                 .sex(wxMpUser.getSex())
                                                 .city(wxMpUser.getCity())
                                                 .sexDesc(wxMpUser.getSexDesc())
                                                 .headImgUrl(wxMpUser.getHeadImgUrl())
                                                 .nickname(wxMpUser.getNickname())
                                                 .country(wxMpUser.getCountry())
                                                 .province(wxMpUser.getProvince())
                                                 .build());
    }
}
